<template>
  <div class="exam-list-page">
    <van-nav-bar title="考试列表" left-arrow @click-left="onClickLeft" />

    <div class="content-container">
      <!-- 顶部筛选 -->
      <van-tabs v-model:active="activeTab" sticky>
        <van-tab title="全部"></van-tab>
        <van-tab title="进行中"></van-tab>
        <van-tab title="即将开始"></van-tab>
        <van-tab title="已结束"></van-tab>
      </van-tabs>

      <!-- 考试列表 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" size="24px" />
      </div>

      <template v-else>
        <div v-if="filteredExams.length > 0" class="exam-list">
          <div
            v-for="exam in filteredExams"
            :key="exam._id"
            class="exam-card"
            @click="goToExamDetail(exam._id)"
          >
            <div class="exam-header">
              <div class="exam-name">{{ exam.exam_name }}</div>
              <div class="exam-status" :class="getStatusClass(exam)">
                {{ getStatusText(exam) }}
              </div>
            </div>
            <div class="exam-info">
              <div class="info-item">
                <van-icon name="clock-o" />
                <span
                  >考试时间:
                  {{ formatTimeRange(exam.start_time, exam.end_time) }}</span
                >
              </div>
              <div class="info-item">
                <van-icon name="todo-list-o" />
                <span>试卷名称: {{ exam.paper?.paper_name || "未知" }}</span>
              </div>
              <div class="info-item">
                <van-icon name="question-o" />
                <span
                  >题目数量:
                  {{ exam.paper?.question_list?.length || 0 }}题</span
                >
              </div>
              <div class="info-item">
                <van-icon name="underway-o" />
                <span>考试时长: {{ exam.paper?.duration || 0 }}分钟</span>
              </div>
            </div>
            <div class="exam-footer">
              <van-button
                v-if="getExamActionType(exam) === 'start'"
                type="primary"
                size="small"
                @click.stop="goToExam(exam._id)"
              >
                开始考试
              </van-button>
              <van-button
                v-else-if="getExamActionType(exam) === 'view'"
                plain
                type="primary"
                size="small"
                @click.stop="goToExamDetail(exam._id)"
              >
                查看详情
              </van-button>
              <span v-else class="exam-hint">{{ getExamHint(exam) }}</span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <van-empty description="暂无符合条件的考试" />
        </div>
      </template>
    </div>

    <!-- 底部导航 -->
    <van-tabbar route>
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="notes-o" to="/history">历史</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  ref,
  watch,
} from 'vue';

import { showToast } from 'vant';
import { useRouter } from 'vue-router';

import { useExamStore } from '../../stores/exam';

const router = useRouter();
const examStore = useExamStore();

const loading = ref(true);
const activeTab = ref(0);

// 获取考试列表
onMounted(async () => {
  try {
    await examStore.fetchExamList();
  } catch (error) {
    console.error("获取考试列表失败", error);
    showToast("获取考试列表失败");
  } finally {
    loading.value = false;
  }
});

// 根据标签筛选考试
const filteredExams = computed(() => {
  if (!examStore.examList) return [];

  const now = new Date().getTime();

  switch (activeTab.value) {
    case 1: // 进行中
      return examStore.examList.filter((exam) => {
        const startTime = new Date(exam.start_time).getTime();
        const endTime = new Date(exam.end_time).getTime();
        return now >= startTime && now <= endTime;
      });
    case 2: // 即将开始
      return examStore.examList.filter((exam) => {
        const startTime = new Date(exam.start_time).getTime();
        return now < startTime;
      });
    case 3: // 已结束
      return examStore.examList.filter((exam) => {
        const endTime = new Date(exam.end_time).getTime();
        return now > endTime;
      });
    default: // 全部
      return examStore.examList;
  }
});

// 获取考试状态文本
const getStatusText = (exam: any) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();
  const endTime = new Date(exam.end_time).getTime();

  if (now >= startTime && now <= endTime) {
    return "进行中";
  } else if (now < startTime) {
    return "即将开始";
  } else {
    return "已结束";
  }
};

// 获取状态样式类
const getStatusClass = (exam: any) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();
  const endTime = new Date(exam.end_time).getTime();

  if (now >= startTime && now <= endTime) {
    return "status-ongoing";
  } else if (now < startTime) {
    return "status-upcoming";
  } else {
    return "status-ended";
  }
};

// 获取考试操作类型
const getExamActionType = (exam: any) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();
  const endTime = new Date(exam.end_time).getTime();

  if (now >= startTime && now <= endTime) {
    return "start"; // 可以开始考试
  } else if (now > endTime) {
    return "view"; // 查看详情
  } else {
    return "wait"; // 等待开始
  }
};

// 获取考试提示文本
const getExamHint = (exam: any) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();

  if (now < startTime) {
    const diff = startTime - now;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

    if (days > 0) {
      return `还有 ${days} 天 ${hours} 小时开始`;
    } else {
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      return `还有 ${hours} 小时 ${minutes} 分钟开始`;
    }
  }

  return "";
};

// 格式化时间范围
const formatTimeRange = (startTime: string, endTime: string) => {
  const start = new Date(startTime);
  const end = new Date(endTime);

  const formatDate = (date: Date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = String(date.getMinutes()).padStart(2, "0");

    return `${month}月${day}日 ${hour}:${minute}`;
  };

  return `${formatDate(start)} - ${formatDate(end)}`;
};

// 返回
const onClickLeft = () => {
  router.back();
};

// 去考试详情页
const goToExamDetail = (id: string) => {
  console.log('goToExamDetail 调用:', { id, type: typeof id })
  router.push(`/exam-detail/${id}`);
};

// 去考试页
const goToExam = (id: string) => {
  debugger;
  router.push(`/exam/${id}`);
};
</script>

<style scoped>
.exam-list-page {
  padding-bottom: 60px;
}

.content-container {
  padding: 0 0 16px 0;
}

.exam-list {
  padding: 16px;
}

.exam-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.exam-name {
  font-size: 16px;
  font-weight: 600;
}

.exam-status {
  font-size: 14px;
  font-weight: 500;
}

.status-ongoing {
  color: #1989fa;
}

.status-upcoming {
  color: #ff976a;
}

.status-ended {
  color: #969799;
}

.exam-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #646566;
}

.info-item :deep(.van-icon) {
  margin-right: 8px;
  font-size: 16px;
}

.exam-footer {
  display: flex;
  justify-content: flex-end;
}

.exam-hint {
  font-size: 14px;
  color: #969799;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}
</style>
